import React, { FC, memo, ReactNode, useEffect, useState } from 'react'
import { Dropdown, Table } from 'antd'
import { IContentConfig } from '@/components/page-content/type'
import { myShallowEqual, useMyDispatch, useMySelector } from '@/store'
import { EllipsisOutlined } from '@ant-design/icons'
import { TableRowSelection } from 'antd/es/table/interface'
import { PagesKey } from '@/global/constant'
import {
  changeCurrentRecordAction,
  changePropIdsAction
} from '@/store/module/main/page-common'

interface IProps {
  children?: (
    text: string | number,
    record: any,
    customkey: string
  ) => ReactNode // 渲染单元格内容的函数
  tableData: any[] // 表格数据源
  config: IContentConfig // 表格配置项
  // key：批量操作，或者编辑、删除之类的按钮的标识； record：当前行的信息
  actionClick?: (key: any, record: any) => void // 更多操作中某一项被点击时触发的回调函数
}

const BaseTable: FC<IProps> = (props) => {
  // 获取redux中的dispatch方法
  const dispatch = useMyDispatch()
  // 解构传入的参数
  const { tableData, config, children } = props
  // 解构表格配置项
  const {
    pageKey,
    tableConfig,
    tableItems,
    isShowRowSelection = false,
    isShowMoreAction = true,
    moreActions = []
  } = config
  // 获取isLoading状态，用于显示loading状态
  const { isLoading } = useMySelector(
    (state) => ({
      isLoading: state.pageCommon.isLoading,
      currentRecord: state.pageCommon.currentRecord
    }),
    myShallowEqual
  )
  // 维护一个新的数据源，用于支持选择行和更多操作功能
  const [newTableData, setNewTableData] = useState(tableData)

  // table选择相关
  // 记录被选中的行的key值
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  // 当用户选择行数据时触发的回调函数
  const onSelectChange = (
    newSelectedRowKeys: React.Key[],
    checkedRecords: any
  ) => {
    let propId = ''
    // 处理propId的值，不同页面的值不一样
    pageKey === PagesKey.UserList && (propId = 'userId')
    pageKey === PagesKey.SensitiveLexIcon && (propId = 'sensitiveWordId')
    pageKey === PagesKey.SensitiveReplace && (propId = 'replaceId')
    pageKey === PagesKey.QuestionList && (propId = 'questionId')
    // 处理返回ids集合
    const checkedIds = checkedRecords.map((item: any) => item[propId])
    // console.log('selectedRowKeys changed: ', checkedIds, checkedRecords)
    // 将ids更新到仓库
    dispatch(changePropIdsAction(checkedIds))
    // 更新页面状态
    setSelectedRowKeys(newSelectedRowKeys)
  }

  // 表格选择框的配置项
  const rowSelection: TableRowSelection<any> = {
    selectedRowKeys,
    onChange: onSelectChange
  }

  useEffect(() => {
    // 每次表格数据源变化时，清空已选中的行数据
    setSelectedRowKeys([])
  }, [newTableData])

  //  ====================== 回调 =======================
  // 点击更多操作的某一项
  const onActionClick = (key: any, record: any) => {
    props.actionClick?.(key, record)
    dispatch(changeCurrentRecordAction(record))
    console.log('操作：', key)
    console.log('当前行：', record)
  }

  // 递归渲染表格列
  function recurseRenderChild(items: any[]) {
    const arr: any[] = []
    items.forEach((item) => {
      if (item.children) {
        const el = (
          // 处理表格列的多级表头
          <Table.ColumnGroup
            title={item.title}
            dataIndex={item.dataIndex}
            key={item.dataIndex as string}
          >
            {recurseRenderChild(item.children)}
          </Table.ColumnGroup>
        )
        arr.push(el)
      } else {
        const el = (
          <Table.Column
            title={item.title}
            width={item.width}
            key={'column-' + item.dataIndex}
            dataIndex={item.dataIndex}
            render={(text: string | number, record: any) => {
              if (item.customkey) {
                return children?.(text, record, item.customkey)
              } else {
                return <span>{text}</span>
              }
            }}
          />
        )
        arr.push(el)
      }
    })
    return arr
  }

  useEffect(() => {
    const data = [...tableData]
    const newData: any[] = []
    data.forEach((item, index) => {
      const newItem = { ...item, key: index }
      newData.push(newItem)
    })
    setNewTableData(newData)
  }, [tableData])

  return (
    <Table
      rowSelection={isShowRowSelection ? rowSelection : undefined}
      {...tableConfig}
      dataSource={newTableData}
      loading={isLoading}
      pagination={false}
    >
      {recurseRenderChild(tableItems)}
      {/*更多操作*/}
      {isShowMoreAction && (
        <Table.Column
          title="操作"
          // width={item.width}
          key="action"
          fixed="right"
          render={(text: any, record: any) => (
            <Dropdown
              menu={{
                items: moreActions,
                onClick: ({ key }) => onActionClick(key, record)
              }}
            >
              <EllipsisOutlined style={{ cursor: 'pointer' }} />
            </Dropdown>
          )}
        />
      )}
    </Table>
  )
}

export default memo(BaseTable)
